package com.example.monitor.controller;

import com.example.monitor.config.JwtTokenUtil;
import com.example.monitor.model.DO.User;
import com.example.monitor.model.DTO.RetrievePasswordDTO;
import com.example.monitor.model.DTO.UserLoginDTO;
import com.example.monitor.model.VO.LoginVO;
import com.example.monitor.model.DTO.Result;
import com.example.monitor.model.VO.ResultVO;
import com.example.monitor.service.AuthService;
import com.example.monitor.service.UserService;
import com.example.monitor.service.impl.AuthServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    private final AuthService authService;

    // 注册
    @PostMapping("/register")
    public ResponseEntity<User> register(@RequestBody User user) {
        User savedUser = userService.registerUser(user);
        return ResponseEntity.ok(savedUser);
    }

    // 登录
    @PostMapping("/login")
    public ResponseEntity<?> loginUser(@RequestBody User user) {
        try {
            String token = userService.loginUser(user.getUsername(), user.getPasswordHash())
                    .orElseThrow(() -> new BadCredentialsException("用户名或密码错误"));
            return ResponseEntity.ok(token);
        } catch (BadCredentialsException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
        }
    }

    @PostMapping("/retrievePassword")
    public ResultVO<Void> retrievePassword(@RequestBody RetrievePasswordDTO dto) {
        authService.retrievePassword(dto);
        return ResultVO.success("密码修改成功");
    }

    // 令牌验证
    @GetMapping("/validate")
    public ResponseEntity<Map<String, Object>> validateToken(@RequestHeader("Authorization") String authHeader) {
        Map<String, Object> response = new HashMap<>();

        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            response.put("isValid", false);
            return ResponseEntity.ok(response);
        }

        String token = authHeader.substring(7);
        try {
            String username = jwtTokenUtil.extractUsername(token);
            if (username != null) {
                UserDetails userDetails = userService.loadUserByUsername(username);
                boolean isValid = jwtTokenUtil.validateToken(token, userDetails);
                response.put("isValid", isValid);
                if (isValid) {
                    response.put("user", userDetails);
                }
                return ResponseEntity.ok(response);
            }
        } catch (Exception e) {
            // Token is invalid
        }

        response.put("isValid", false);
        return ResponseEntity.ok(response);
    }


}